library ykfview;

import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_swiper_view/flutter_swiper_view.dart';

class YKLoopWidgetController {

  YKLoopWidget? _widget;

  void resetWidget(List<Widget> widgets) {
    _widget?.widgets = widgets;
    _widget?._state.setState(() { });
  }

  void scrollTo(int index, {bool animation = true}) {
    _widget?._state.swiperController.move(index, animation: animation);
  }
}


class YKLoopWidget extends StatefulWidget {

  List<Widget> widgets;
  final bool autoCountdown;
  Duration? scrollTime;
  YKLoopWidgetController? _controller;

  YKLoopWidget({
    super.key,
    required this.widgets,
    this.autoCountdown = false,
    this.scrollTime,
    YKLoopWidgetController? controller
  }) {
    _controller = controller;
    _controller?._widget = this;
  }

  _YKLoopWidgetState _state = _YKLoopWidgetState();

  @override
  State<StatefulWidget> createState() => _state;
}

class _YKLoopWidgetState extends State<YKLoopWidget> {

  SwiperController swiperController = SwiperController();

  Timer? _timer;

  @override
  void initState() {
    if (widget.autoCountdown) {
      swiperController.startAutoplay(animation: true);
    }
    super.initState();
  }

  @override
  void dispose() {
    // _endTime();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) => _main();

  Widget _main() {
    return Swiper(
      itemCount: widget.widgets.length,
      controller: swiperController,
      itemBuilder: (context, index) {
        return widget.widgets[index];
      },
    );
  }

  // void _beginTime() {
  //   _timer?.cancel();
  //   _timer = Timer.periodic(widget.scrollTime ?? Duration(seconds: 2), (timer) {
  //     _next();
  //   });
  // }
  // void _endTime() {
  //
  //   _timer?.cancel();
  //   _timer = null;
  //
  // }
  //
  // void _next() {
  //   swiperController.next(animation: true);
  // }
}
